<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleCancel" center width="50%">
       <template v-slot:title>
        <div class="dialog-title">
          <div>{{title}}</div>
          <div class="dialog-btn cursor iconfont" :class="[isDialogShow ? 'icon-yanjing': 'icon-biyan']" @click="handleClickDialogIsShow"></div>
        </div>
      </template>
      <el-form v-if="dialogVisible" ref="editFormRef" :model="editForm" :rules="rules" label-width="100px" size="small">
        <el-form-item label="部门名称" prop="deptName">
          <el-input placeholder="请输入部门名称" v-model="editForm.deptName"></el-input>
        </el-form-item>

        <el-form-item label="部门级别" prop="deptLevel">
          <el-select placeholder="请选择部门级别" v-model="editForm.deptLevel" @change="deptLevelChange">
            <el-option v-for="item in deptLevel" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="部门主管" prop="teacherNo">
          <el-select  v-model="editForm.teacherNo"
            clearable
            placeholder="请选择部门主管"
            filterable
          >
            <el-option
              v-for="item in teacherList"
              :key="item.no"
              :label="item.name"
              :value="item.no"
            >
            <div @click="changeTeacher(item)">{{item.name}}</div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="主管电话" prop="teacherPhone">
            <Acc-desensitization disabled ref="cellularPhone" rule-type='cellularPhone' v-model="editForm.teacherPhone"></Acc-desensitization>
        </el-form-item>

        <el-form-item label="上级部门" prop="parentNo" :show-message="deptLevelValue === 1 ? false : true">
          <el-input
            ref="deptInput"
            :disabled="disabled"
            placeholder="请选择上级部门"
            @focus="deptFocus"
            v-model="editForm.parentDeptName"
          ></el-input>
        </el-form-item>

        <el-form-item label="是否启用" prop="isEnable">
          <el-radio-group v-model="editForm.isEnable">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            placeholder="请输入备注"
            type="textarea"
            v-model="editForm.remark"
            :maxlength="100"
            :autosize="{ minRows: 4, maxRows: 6 }"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel" size="small">取 消</el-button>
        <el-button type="primary" @click="handleOk('editFormRef')" size="small">确 定</el-button>
      </div>
    </el-dialog>
    <dept-tree-modal
      ref="deptModal"
      :checkDeptInfo="checkDeptInfo"
      :isOnlyShowParent="true"
      :deptLevel="deptLevelValue"
      @deptModalOk="deptModalOk"
    ></dept-tree-modal>
  </div>
</template>

<script>
import { teacherList } from '../js/gradeInfo'
import { deptLevel } from '@/views/children/auth/js/constants'
import DeptTreeModal from './DeptTreeModal'
import { addDepartmentInfo, updateDepartmentInfo } from '@/views/children/basic/js/departmentInfo'
import pick from 'lodash.pick'

export default {
  name: 'DepartmentModal',
  components: { DeptTreeModal },
  model: {
    prop: 'oncE',
    event: 'change'
  },
  props: {
    oncE: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      isDialogShow: true,
      title: '部门新增',
      dialogVisible: false, // 编辑弹窗
      disabled: true,
      editForm: {
        deptName: '',
        deptLevel: '',
        teacherNo: '',
        teacherPhone: '',
        teacherName: '',
        parentNo: '',
        isEnable: '',
        remark: '',
        parentDeptName: ''
      },
      model: {},
      rules: {
        deptName: [{ required: true, validator: this.validateDeptName }],
        deptLevel: [{ required: true, message: '请选择部门级别!' }],
        teacherNo: [{ required: true, message: '请选择部门主管!' }],
        parentNo: [{ required: true, message: '请选择上级部门!' }],
        isEnable: [{ required: true, message: '请选择是否启用!' }]
      },
      deptLevel,
      checkDeptInfo: {},
      deptLevelValue: 0,
      teacherList: [],
      oldTeacher: '',
      once: 0
    }
  },
  mounted () {
    this.getTeacherList()
  },
  watch: {
    // 校验规则替换
    deptLevelValue (val) {
      if (val === 1) {
        this.rules.parentNo[0].required = false
        this.disabled = true
      } else {
        this.rules.parentNo[0].required = true
        this.disabled = false
      }
    },
    //

    editForm: {
      handler (newVal, oldVal) {
        if (newVal.parentNo === '0') {
          // this.editForm.parentNo = ''
        }
      }
    },
    'editForm.teacherNo': {
      handler () {

      }
    },
    oncE (val) {
      this.once = val
    }
  },
  methods: {
    handleClickDialogIsShow () {
      this.isDialogShow = !this.isDialogShow
      this.$refs.cellularPhone.doShow()
    },
    // 新增
    add () {
      this.edit({}, 0)
    },
    // 编辑
    edit (record, once) {
      this.once = once

      this.model = Object.assign({}, record)
      if (record.id) {
        this.title = '编辑部门'
        const { parentNo: no, parentDeptName: deptName, deptLevel } = record
        this.checkDeptInfo = {
          no: no,
          deptName
        }
        this.deptLevelValue = deptLevel
        // this.$nextTick(() => {
        //   this.editForm = pick(
        //     this.model,
        //     'deptName',
        //     'deptLevel',
        //     'teacherNo',
        //     'teacherPhone',
        //     'teacherName',
        //     'parentNo',
        //     'parentDeptName',
        //     'isEnable',
        //     'remark'
        //   )
        // })
        // console.log(this.model.teacherName)
        if (!this.model.teacherName || this.model.teacherName === '') {
          this.$nextTick(() => {
            this.editForm = pick(
              this.model,
              'deptName',
              'deptLevel',
              'teacherPhone',
              'teacherName',
              'parentNo',
              'parentDeptName',
              'isEnable',
              'remark'
            )
          })
        } else {
          this.$nextTick(() => {
            this.editForm = pick(
              this.model,
              'deptName',
              'deptLevel',
              'teacherNo',
              'teacherPhone',
              'teacherName',
              'parentNo',
              'parentDeptName',
              'isEnable',
              'remark'
            )
          })
        }
      } else {
        this.deptLevelValue = 1
        this.editForm = {}
        this.editForm.parentDeptName = ''
        this.title = '添加部门'
      }
      this.$nextTick(() => {
        this.dialogVisible = true
      })
    },

    async  getTeacherList () {
      let res = await teacherList({})
      console.log(res)
      this.teacherList = res.data
    },
    // 提交表单
    handleOk (editFormRef) {
      this.$refs[editFormRef].validate(async valid => {
        if (valid) {
          let vle = JSON.parse(JSON.stringify(this.editForm))
          delete vle.parentDeptName
          delete vle.teacherName
          delete vle.teacherPhone
          let values
          if (this.once === 1) {
            // vle.teacherNo = this.oldTeacher
          }
          values = {
            ...vle,
            parentNo: this.checkDeptInfo.no || '0'
          }
          console.log(values)

          let res, msg
          if (!this.model.id) {
            res = await addDepartmentInfo(values)
            msg = '保存成功！'
          } else {
            console.log(Object.assign({}, values, { deptId: this.model.id }))
            res = await updateDepartmentInfo(Object.assign({}, values, { deptId: this.model.id }))
            msg = '修改成功！'
          }
          if (res.code === 0) {
            this.$message.success(msg)
          } else {
            this.$message.warning(res.msg)
          }
          this.$emit('ok')
          this.handleCancel()
        }
      })
    },

    // 上级部门弹框回调
    deptModalOk (val) {
      console.log(val)
      this.checkDeptInfo = val
      this.editForm.parentDeptName = val.deptName
      this.editForm.parentNo = val.no
    },

    // 部门级别改变
    deptLevelChange (val) {
      this.deptLevelValue = val
      this.editForm.parentDeptName = ''
      this.editForm.parentNo = ''
      if (val === 1) {
        this.checkDeptInfo['no'] = 0
      }
    },

    // 获取焦点弹框
    deptFocus () {
      this.$refs.deptModal.add()
      this.$refs.deptInput.blur()
    },

    // 取消
    handleCancel () {
      this.dialogVisible = false
      this.$refs.editFormRef.resetFields()
      this.deptLevelValue = 1
      this.editForm.parentDeptName = ''
      this.checkDeptInfo = {}
    },
    strlen (str) {
      var len = 0
      for (var i = 0; i < str.length; i++) {
        var c = str.charCodeAt(i)
        // 单字节加1
        if ((c >= 0x0001 && c <= 0x007e) || (c >= 0xff60 && c <= 0xff9f)) {
          len++
        } else {
          len += 2
        }
      }
      return len
    },
    validateDeptName (rule, value, callback) {
      if (value) {
        if (value.toString().trim() === '') {
          callback(new Error('请输入部门名称'))
        } else if (this.strlen(value) > 30) {
          callback(new Error('部门名称不能超过30个字符'))
        } else {
          callback()
        }
      } else {
        callback(new Error('请输入部门名称'))
      }
    },
    changeTeacher (e) {
      this.editForm.teacherPhone = e.contact
      this.$nextTick(() => {
        this.$refs.cellularPhone.init(this.editForm.teacherPhone)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-right: 25px;

  .dialog-btn {
    font-size: 18px;
  }
}
</style>
